package com.artron.mediaartron.ui.fragment.made.picture;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.artron.mediaartron.R;
import com.artron.mediaartron.ui.activity.PictureViewActivity;
import com.artron.mediaartron.ui.adapter.PictureSelectionAdapter;
import com.artron.mediaartron.ui.fragment.dialog.NormalDialogFragment;
import com.artron.mediaartron.ui.helper.SpacesItemDecoration;
import com.artron.mediaartron.ui.widget.MediaImageLayout;
import com.bilibili.boxing.AbsBoxingViewFragment;
import com.bilibili.boxing.Boxing;
import com.bilibili.boxing.model.BoxingManager;
import com.bilibili.boxing.model.config.BoxingConfig;
import com.bilibili.boxing.model.entity.BaseMedia;
import com.bilibili.boxing.model.entity.impl.ImageMedia;
import com.bilibili.boxing.utils.BoxingFileHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;


/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-09-25.
 */

public class PictureSelectionFragment extends AbsBoxingViewFragment implements MediaSelectCallback{

    private static final int IMAGE_CROP_REQUEST_CODE = 9087;
    private static final int IMAGE_PREVIEW_REQUEST_CODE = 9086;
    public static final String TAG = "PictureSelection";
    @BindView(R.id.General_recycler)
    protected RecyclerView mRecyclerView;

    private PictureSelectionAdapter mMediaAdapter;
    private ProgressDialog mDialog;


    private boolean mIsCamera;
    private boolean mIsSelected;
    private boolean mIsHaveParentFragment;

    public static PictureSelectionFragment newInstance(boolean isHaveParent) {
        PictureSelectionFragment fragment = new PictureSelectionFragment();
        fragment.init(isHaveParent);
        return fragment;
    }

    private void init(boolean isHaveParent) {
        this.mIsHaveParentFragment = isHaveParent;
    }

    public void init(List<BaseMedia> medias) {
        mMediaAdapter.addAllData(medias);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.general_recycler, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.General_recycler);
        initRecycleView();
        super.onViewCreated(view, savedInstanceState);

        setHasOptionsMenu(!mIsHaveParentFragment);
    }

    private void initRecycleView() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        gridLayoutManager.setSmoothScrollbarEnabled(true);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        mRecyclerView.addItemDecoration(new SpacesItemDecoration(getResources()
                .getDimensionPixelOffset(R.dimen.boxing_media_margin), 3));

        mMediaAdapter = new PictureSelectionAdapter(getActivity());
        mMediaAdapter.setOnCameraClickListener(new OnCameraClickListener());
        mMediaAdapter.setOnCheckedListener(new OnMediaCheckedListener());
        mMediaAdapter.setOnMediaClickListener(new OnMediaClickListener());
        mRecyclerView.setAdapter(mMediaAdapter);
    }

    @Override
    public void startLoading() {
        loadMedias();
    }

    @Override
    public void onCreateWithSelectedMedias(Bundle bundle, @Nullable List<BaseMedia> selectedMedias) {
        if (selectedMedias != null) {
            for (BaseMedia selectedMedia : selectedMedias) {
                Log.d(TAG.substring(5), "onCreateWithSelectedMedias: " + selectedMedia);
            }
        }

        super.onCreateWithSelectedMedias(bundle, selectedMedias);
    }

    @Override
    public void showMedia(@Nullable List<BaseMedia> medias, int allCount) {
        if (medias != null) {
            init(medias);
            for (BaseMedia selectedMedia : medias) {
                Log.d(TAG.substring(5), "showMedia: " + selectedMedia);
            }
        }

        super.showMedia(medias, allCount);
    }

    @Override
    public void onRequestPermissionError(String[] permissions, Exception e) {
        if (permissions.length > 0) {
            if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(getContext(), "需要访问你的存储设备来选择图片，请在“系统设置”或授权对话框中允许“存储空间”权限。", Toast.LENGTH_SHORT).show();
            } else if (permissions[0].equals(Manifest.permission.CAMERA)){
                Toast.makeText(getContext(), "需要访问你的相机来拍照，请在“系统设置”或授权对话框中允许“使用相机”权限。", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onRequestPermissionSuc(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (permissions[0].equals(STORAGE_PERMISSIONS[0])) {
            startLoading();
        } else if (permissions[0].equals(CAMERA_PERMISSIONS[0])) {
            startCamera(getActivity(), this, null);
        }
    }

    @Override
    public void onCameraActivityResult(int requestCode, int resultCode) {
        showProgressDialog();
        super.onCameraActivityResult(requestCode, resultCode);
    }

    @Override
    public void onCameraFinish(BaseMedia media) {
        dismissProgressDialog();

        setCamera(false);
        if (media == null) {
            return;
        }
        if (hasCropBehavior()) {
            startCrop(media, IMAGE_CROP_REQUEST_CODE);
        } else if (getSelectedMedias() != null) {
            List<BaseMedia> selectedMedias = getSelectedMedias();
            selectedMedias.add(media);
            onFinish(selectedMedias);
        }
    }

    @Override
    public void onCameraError() {
        setCamera(false);
        dismissProgressDialog();
    }

    private void showProgressDialog() {
        if (mDialog == null) {
            mDialog = new ProgressDialog(getActivity());
            mDialog.setIndeterminate(true);
            mDialog.setMessage("处理中");
        }
        if (!mDialog.isShowing()) {
            mDialog.show();
        }
    }

    private void dismissProgressDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.hide();
            mDialog.dismiss();
        }
    }


    private class OnCameraClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            if (!mIsCamera) {
                mIsCamera = true;
                startCamera(getActivity(), PictureSelectionFragment.this,
                            BoxingFileHelper.DEFAULT_SUB_DIR);
            }
        }
    }

    private class OnMediaClickListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
//            ImageMedia imageMedia = (ImageMedia) view.getTag();
//            MediaImageLayout imageLayout = ((MediaImageLayout) view);
//            setCheckView(imageMedia, imageLayout);

            BaseMedia media = (BaseMedia) view.getTag();
            int pos = (int) view.getTag(R.id.PictureSelectionFragmentItem_iv_check);
            BoxingConfig.Mode mode = BoxingManager.getInstance().getBoxingConfig().getMode();
            if (mode == BoxingConfig.Mode.SINGLE_IMG || mode == BoxingConfig.Mode.MULTI_IMG) {
                multiImageClick(pos);
            } else if (mode == BoxingConfig.Mode.VIDEO) {
//                videoClick(media);
            }
        }

        private void multiImageClick(int pos) {
            ArrayList<BaseMedia> medias = (ArrayList<BaseMedia>) mMediaAdapter.getSelectedMedias();
            Boxing.get().withIntent(getContext(), PictureViewActivity.class, medias, pos)
                    .start(PictureSelectionFragment.this, PictureSelectionFragment.IMAGE_PREVIEW_REQUEST_CODE,
                            BoxingConfig.ViewMode.EDIT);

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_PREVIEW_REQUEST_CODE) {
            boolean isBackClick = data.getBooleanExtra(PictureViewActivity.EXTRA_TYPE_BACK, false);
            List<BaseMedia> selectedMedias = data.getParcelableArrayListExtra(Boxing.EXTRA_SELECTED_MEDIA);
            onViewActivityRequest(selectedMedias, mMediaAdapter.getAllMedias(), isBackClick);
            if (isBackClick) {
                mMediaAdapter.setSelectedMedias(selectedMedias);
                mMediaAdapter.notifyDataSetChanged();
            }
            updateMultiPickerLayoutState(selectedMedias);
        }
    }

    private void onViewActivityRequest(List<BaseMedia> selectedMedias, List<BaseMedia> allMedias, boolean isBackClick) {
        if (isBackClick) {
            checkSelectedMedia(allMedias, selectedMedias);
        } else {
            onFinish(selectedMedias);
        }
    }

    private void updateMultiPickerLayoutState(List<BaseMedia> medias) {
//        updateOkBtnState(medias);
//        updatePreviewBtnState(medias);
    }

    private void setCheckView(ImageMedia imageMedia, MediaImageLayout itemLayout) {
        boolean isSelected = !imageMedia.isSelected();

        BoxingConfig.Mode mode = BoxingManager.getInstance().getBoxingConfig().getMode();
        if (mode == BoxingConfig.Mode.SINGLE_IMG) {
            List<BaseMedia> allMedias = mMediaAdapter.getAllMedias();
            for (int x = 0; x < allMedias.size(); x++) {
                ImageMedia media = (ImageMedia) allMedias.get(x);
                if (isSelected) {
                    media.setSelected(false);
                }
            }
        } else {

        }


        List<BaseMedia> selectedMedias = mMediaAdapter.getSelectedMedias();
        selectedMedias.clear();
        selectedMedias.add(imageMedia);

        imageMedia.setSelected(isSelected);
        itemLayout.setChecked(isSelected);
        mMediaAdapter.notifyDataSetChanged();

        if (mIsHaveParentFragment) {
            ((TabFragment) getParentFragment()).setCheckView(isSelected);
        } else {
            setCheckView(isSelected);
        }
    }

    private class OnMediaCheckedListener implements PictureSelectionAdapter.OnMediaCheckedListener {

        @Override
        public void onChecked(View view, BaseMedia iMedia) {
            if (!(iMedia instanceof ImageMedia)) {
                return;
            }
            setCheckView(((ImageMedia) iMedia), ((MediaImageLayout) view));
        }
    }

    public void setCamera(boolean camera) {
        mIsCamera = camera;
    }

    public List<BaseMedia> getSelectedMedias() {
        return mMediaAdapter.getSelectedMedias();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_selection:
                if (mIsSelected) {
                    List<BaseMedia> selectedMedias = getSelectedMedias();
                    BaseMedia imageMedia = selectedMedias.get(0);
                    float size = imageMedia.getSize() / 1024.f;
                    if (size < 500) {
                        NormalDialogFragment dialog = NormalDialogFragment.newInstance("提示",
                                "为保证打印质量，请选择500kb以上的图片", "", "我知道了");
                        dialog.show(getChildFragmentManager(), dialog.getOurTag());
                    } else {
                        onFinish(selectedMedias);
                    }
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        MenuItem item = menu.findItem(R.id.menu_selection);
        if (mIsSelected) {
            item.setIcon(R.drawable.ic_selection_finish_selected);
        } else {
            item.setIcon(R.drawable.ic_selection_finish_normal);
        }
        super.onPrepareOptionsMenu(menu);
    }

    public void setCheckView(boolean isSelected) {
        this.mIsSelected = isSelected;
        getActivity().invalidateOptionsMenu();
    }
}
